package com.daxt.utils;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.common.util.DateUtil;
import com.daxt.model.dic.SystemConfigType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.daxt.mapper.sys.DataBackupsMapper;
import com.daxt.mapper.use.UseBorrowRecordMapper;
import com.daxt.model.service.base.vo.DataBackups;
import com.daxt.model.service.use.vo.UseBorrowRecord;

@Component
public class ScheduledTask {
    @Autowired
    private UseBorrowRecordMapper useBorrowRecordMapper;
    //	@Value(value = "${systemConfig.tempPath}")
//	private String tempPath;
    @Autowired
    private DataBackupsMapper dataBackupsMapper;
    @Value(value = "${spring.datasource.password}")
    private String mysqlusername;
    @Value(value = "${spring.datasource.username}")
    private String mysqlpassword;
    @Value(value = "${spring.datasource.url}")
    private String mysqlUrl;


    //借阅到期定时
    // @Scheduled(cron = "0/5 * * * * *")
//    @Scheduled(cron = "0 0 2 * * ?")//[秒] [分] [小时] [日] [月] [周] [年]
//    每天凌晨1点执行一次："0 0 1 * * ?"
//    @Scheduled(cron = "30 * * * * ?")//30秒执行
    @Scheduled(cron = "0 0 1 * * ?")//每天凌晨1点执行一次
    public void fixedRate() {
        QueryWrapper<UseBorrowRecord> queryWrapper = new QueryWrapper<UseBorrowRecord>();
        queryWrapper.eq("state", "2");
        List<UseBorrowRecord> list = useBorrowRecordMapper.selectList(queryWrapper);
        for (UseBorrowRecord useBorrowRecord : list) {
            String startTime = useBorrowRecord.getStartTime();
            String endTime = useBorrowRecord.getEndTime();
            String currentTime = DateUtil.getCurrentTime(DateUtil.DateFormat.YYYY_MM_DD);
            if (currentTime.compareTo(endTime) >= 0) {
//            if (endTime.compareTo(startTime) > 0) {
                UseBorrowRecord u = new UseBorrowRecord();
                u.setId(useBorrowRecord.getId());
                u.setState("3");
                useBorrowRecordMapper.updateById(u);
            }
        }
    }

//    @Scheduled(cron = "0 */1 * * * ?")//每隔1分钟执行一次：
    @Scheduled(cron = "0 0 1 * * ?")
    public void clearTemp() {
        System.out.println("删除文件");
        // deleteFolder(new File(tempPath));
        String tempPath = RedisUtil.getSysConfig(SystemConfigType.TEMP_PATH);
        File file = new File(tempPath);
        File[] listFiles = file.listFiles();
        if (listFiles != null && listFiles.length > 0)
            deleteFolder(file.listFiles());
    }
    @Scheduled(cron = "0 0 2 * * ?")
    public void clearDataReceive() {
        System.out.println("删除文件");
        // deleteFolder(new File(tempPath));
        String dataPath = RedisUtil.getSysConfig(SystemConfigType.OSS_DIR );
        File file = new File(dataPath+"receive/");
        File[] listFiles = file.listFiles();
        if (listFiles != null && listFiles.length > 0)
            deleteFolder(file.listFiles());
    }

    public void deleteFolder(File[] file) {
        for (File tempfile : file) {
            if (tempfile.isDirectory()) {
                File[] listFiles = tempfile.listFiles();
                if (listFiles != null && listFiles.length > 0) {
                    deleteFolder(listFiles);
                } else {
                    tempfile.delete();
                }
            } else {
                tempfile.delete();
            }

        }

    }


//    @Scheduled(cron = "0 0 4 * * ?")
//    public void delOssTemp() {
//        //删除对象存储
//        try {
//            MinioUtil.getList("temp");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * @description: 数据库自动备份
     * @author: lig
     * @date: 2021/7/23
     */
    //@Scheduled(cron = "0 0 5 * * ?")
    public void backups() throws IOException, InterruptedException {


        try {
            String type = "1";//自动备份
            String flag = "backup";//备份
            String fileName = IdWorker.getIdStr() + ".sql";
            String dataBaseName=mysqlUrl.substring(mysqlUrl.indexOf("/",27)+1,mysqlUrl.indexOf("?"));
            if (DataBaseUtil.execMysql(fileName, mysqlusername, mysqlpassword, type, flag,"3306",dataBaseName)) {
                DataBackups entity = new DataBackups();
                entity.setCreateTime(LocalDateTime.now());
                entity.setDataType(type);
                entity.setFileName(fileName);
                dataBackupsMapper.insert(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    /**
//     * @description: 获取ekp待办
//     * @author: lig
//     * @date: 2021/7/23
//     */
//    //@Scheduled(cron = "0 0 5 * * ?")
//    public void ekp() {
//
//
//            String type = "1";//自动备份
//            String flag = "backup";//备份
//            String fileName = IdWorker.getIdStr() + ".sql";
//            if (DataBaseUtil.execMysql(fileName, mysqlusername, mysqlpassword, type, flag,"8066")) {
//                DataBackups entity = new DataBackups();
//                entity.setCreateTime(LocalDateTime.now());
//                entity.setDataType(type);
//                entity.setFileName(fileName);
//                dataBackupsMapper.insert(entity);
//            }
//    }


//    public static void main(String[] args){
//        System.out.println("删除文件");
//        // deleteFolder(new File(tempPath));
//        File file = new File(SystemConfig.tempPath);
//        File[] listFiles = file.listFiles();
//        if (listFiles != null && listFiles.length > 0)
//            new ScheduledTask().deleteFolder(file.listFiles());
//    }

}
